package de.listrong.da.ontology;

import gate.Annotation;
import gate.AnnotationSet;

import java.util.Iterator;
import java.util.LinkedList;

/* container for sentence individuals */
public class SentenceList extends LinkedList<SentenceIndividual> {

	private static final long serialVersionUID = -5612854912525180492L;
	
	/**
	 * constructor, read sentence annotation set and create a list of sentence individuals.
	 * @param sentenceAnnoSet
	 */
	public SentenceList(AnnotationSet sentenceAnnoSet) {
		super();
		for (Annotation annotation : sentenceAnnoSet) {
			SentenceIndividual aSentence = new SentenceIndividual(annotation);
			this.add(aSentence); // default oder by beginOffset.
		}
		// Collections.sort(this); 
	}
	
	/**
	 * scan a annotation set. Order a wordIndividual into the wordList of each Sentence.
	 * @param annotationSet
	 */
	public void fillWithAnnotationSet(AnnotationSet annotationSet) {
		for (Annotation annotation : annotationSet) {
			WordIndividual aWord = new WordIndividual(annotation);
			SentenceIndividual parentSentence = this.getSentenceByOffset(aWord);
			try {
				parentSentence.addWord(aWord);
			} catch (Exception e) {
				System.err.println(e);
			}// end of try ... catch
		}
		this.sortWordList();
	}
	
	/**
	 * Method getIdByOffset() return an object of SentenceIndividual by input a word begin offset. 
	 * In this sentence contains the word.
	 * @param a object of WordIndividual
	 * @return the founded sentence or null.
	 */
	private SentenceIndividual getSentenceByOffset(WordIndividual aWord) {
		for (SentenceIndividual aSentence : this) {
			if (aSentence.containTheWord(aWord)) return aSentence;
		}
		return null;
	}

    /* sort method */
	public void sortWordList() {
		for (SentenceIndividual aSentence : this) {
			if(aSentence.getWordList() != null) {
				aSentence.getWordList().sortByOffset();
			}
		}
	}

	/* override method */
	@Override
	public String toString() {
		Iterator<SentenceIndividual> iter = iterator();
		if(!iter.hasNext())
			return  "[]";
		StringBuilder sb = new StringBuilder();
		while(iter.hasNext()) {
			SentenceIndividual sentenceIndi = iter.next();
			sb.append(sentenceIndi + "\n");
		}
		return sb.toString();
	}	
	
}
